package com.abc.rule.aviator;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.type.AviatorLong;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorString;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

public class DayBeforeFunction extends AbstractFunction {

   @Override
   public AviatorObject call(Map<String, Object> env, AviatorObject arg1) {

      try {
         AviatorLong left = (AviatorLong) arg1;

         Integer dayNum = new BigDecimal(left.longValue()).intValue();

         if (dayNum == null) {
            return new AviatorString(formatDate(new Date(), "yyyy-MM-dd"));
         }

         return new AviatorString(getDateBefore(new Date(), dayNum, "yyyy-MM-dd"));
      }
      catch (Exception e) {

         return new AviatorString(formatDate(new Date(), "yyyy-MM-dd"));
      }
   }

   @Override
   public String getName() {
      return "before";
   }


   public String formatDate(Date date, String pattern) {

      if (date == null) {
         return "";
      }

      SimpleDateFormat dateFormator = new SimpleDateFormat(pattern);
      String str = dateFormator.format(date);

      return str;
   }

   public String getDateBefore(Date d, int day, String pattern) {
      Calendar now = Calendar.getInstance();
      now.setTime(d);
      now.set(Calendar.DATE, now.get(Calendar.DATE) - day);

      return formatDate(now.getTime(), pattern);
   }

}